"""
绩效管理
"""
import logging
from datetime import datetime, timedelta

from django.db.models import Sum

from biz.core.thanos.models import Performance
from biz.core.thanos.services import problem_type_service
from biz.utils.export_file import gen_filename, redirect_to_file
from gis.common.django_ext.models import paginate
from gis.admin.services import admin_service

_LOGGER = logging.getLogger(__name__)


def list_performance(pro_id, page_no, page_size, user_id=None, type_id=None, day_start=None, day_end=None):
    assert page_no > 0
    assert page_size > 0
    assert pro_id
    query = Performance.objects.filter(user__pro_id=pro_id).all()
    if type_id:
        query = query.filter(type_id=type_id)
    if user_id:
        query = query.filter(user_id=user_id)
    if day_start:
        query = query.filter(day__gte=day_start)
    if day_end:
        query = query.filter(day__lte=day_end)
    return query.count(), [e.to_dict() for e in paginate(query, page_no, page_size)]


def get_ttl_data(pro_id, user_id=None, type_id=None, day_start=None, day_end=None):
    assert pro_id
    query = Performance.objects.filter(user__pro_id=pro_id).all()
    if type_id:
        query = query.filter(type_id=type_id)
    if user_id:
        query = query.filter(user_id=user_id)
    if day_start:
        query = query.filter(day__gte=day_start)
    if day_end:
        query = query.filter(day__lte=day_end)
    ttl_data = query.aggregate(Sum('finish_count'), Sum('wait_count'), Sum('comment_good_count'),
                               Sum('comment_bad_count'))
    ttl_finish_count = ttl_data['finish_count__sum'] if ttl_data.get('finish_count__sum') else 0
    ttl_wait_count = ttl_data['wait_count__sum'] if ttl_data.get('wait_count__sum') else 0
    ttl_comment_good_count = ttl_data['comment_good_count__sum'] if ttl_data.get('comment_good_count__sum') else 0
    ttl_comment_bad_count = ttl_data['comment_bad_count__sum'] if ttl_data.get('comment_bad_count__sum') else 0
    ttl_good_percent = (ttl_comment_good_count / (
            ttl_comment_good_count + ttl_comment_bad_count)) if ttl_comment_good_count + ttl_comment_bad_count > 0 else 0
    # 计算平均处理时长
    ttl_time = 0
    admin_list = set()
    for e in query:
        ttl_time += e.finish_count * e.avg_process_time
        admin_list.add(e.user_id)
    ttl_avg_process_time = ttl_time / ttl_finish_count if ttl_finish_count > 0 else 0
    # 总操作人数

    return {
        'ttl_admin_count': len(admin_list),
        'ttl_order_count': ttl_finish_count + ttl_wait_count,
        'ttl_finish_count': ttl_finish_count,
        'ttl_wait_count': ttl_wait_count,
        'ttl_comment_good_count': ttl_comment_good_count,
        'ttl_comment_bad_count': ttl_comment_bad_count,
        'ttl_good_percent': ttl_good_percent,
        'ttl_avg_process_time': ttl_avg_process_time
    }


def get_yesterday_good_percent(user_id, type_id):
    yesterday = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
    data = Performance.objects.filter(user_id=user_id).filter(type_id=type_id).filter(day=yesterday).first()
    return data.good_percent if data else 0


def download(pro_id, user_id=None, type_id=None, day_start=None, day_end=None):
    cn_header = ['日期', '操作人', '问题类型', '总单量', '已处理数量', '未处理数量', '平均处理时长', '满意数量', '不满意数量', '满意度']
    filename = gen_filename('performance')
    data = _export_data(pro_id, user_id, type_id, day_start, day_end)
    return redirect_to_file(data, cn_header, filename)


def _export_data(pro_id, user_id=None, type_id=None, day_start=None, day_end=None):
    assert pro_id
    query = Performance.objects.filter(user__pro_id=pro_id).all()
    if type_id:
        query = query.filter(type_id=type_id)
    if user_id:
        query = query.filter(user_id=user_id)
    if day_start:
        query = query.filter(day__gte=day_start)
    if day_end:
        query = query.filter(day__lte=day_end)
    data = []
    user_name_dict = {}
    problem_desc_dict = {}
    for item in query:
        total_count = item.finish_count + item.wait_count
        if user_name_dict.get(item.user_id):
            user_name = user_name_dict[item.user_id]
        else:
            _user = admin_service.get_user_by_id(item.user_id)
            user_name = _user['name']
            user_name_dict[item.user_id] = user_name

        if problem_desc_dict.get(item.type_id):
            problem_desc = problem_desc_dict[item.type_id]
        else:
            _problem = problem_type_service.get_problem_type(item.type_id)
            problem_desc = _problem['desc']
            problem_desc_dict[item.type_id] = problem_desc
        data.append((
            item.day,
            user_name,
            problem_desc,
            total_count,
            item.finish_count,
            item.wait_count,
            '%.2f' % item.avg_process_time,
            item.comment_good_count,
            item.comment_bad_count,
            '%.2f' % (item.good_percent * 100) + '%'
        ))
    return data
